package net.dataforte.tooonebee.log4j;

import static net.dataforte.tooonebee.Menu.menu;

import java.util.Enumeration;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.TreeSet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dataforte.tooonebee.Menu;
import net.dataforte.tooonebee.ServiceIntrospector;

import org.apache.log4j.Appender;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class Log4JIntrospector extends ServiceIntrospector {

	@Override
	public Set<Menu> getMenuEntries() {
		Set<Menu> entries = super.getMenuEntries();
		entries.add(
			menu("Log4J", this.getRequestPath(),
				menu("Loggers", "loggers"),
				menu("Appenders", "appenders")
			)
		);
		return entries;
	}

	@Override
	public String getRequestPath() {
		return "log4j";
	}

	@Override
	public void handleRequest(HttpServlet servlet, HttpServletRequest req, HttpServletResponse res) throws Exception {
		Set<Logger> loggers = new TreeSet<Logger>(new LoggerComparator());
		SortedMap<String, Appender> appenders = new TreeMap<String, Appender>();

		loggers.add(LogManager.getRootLogger());
		for(Enumeration<?> en = LogManager.getCurrentLoggers(); en.hasMoreElements(); ) {
			Logger logger = (Logger) en.nextElement();
			loggers.add(logger);
			for(Enumeration<?> aen = logger.getAllAppenders(); aen.hasMoreElements(); ) {
				Appender appender = (Appender) aen.nextElement();
				appenders.put(appender.getName(), appender);
			}
		}
		
	}

}
